package com.jinlejia.erp.ui.mine.pushmoney;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.MyViewPagerAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.LegendBean;
import com.jinlejia.erp.databinding.ActivityPushMoneyBinding;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class PushMoneyActivity extends AppCompatActivity implements OnDateSetListener {
    // TabLayout中的tab标题  ,
    private String[] mTitles = {"●", "●"};

    // ViewPager的数据适配器
    private MyViewPagerAdapter mViewPagerAdapter;
    ArrayList<LegendBean> list1 = new ArrayList<>();
    ArrayList<LegendBean> list2 = new ArrayList<>();
    LegendContentFragment fragment1;
    LegendContentFragment fragment2;
    private ActivityPushMoneyBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_push_money);
        binding.setEvent(this);

        binding.calendar.setText(DateUtil.getTime(System.currentTimeMillis(), "yyyy-MM"));
        getData();


        // 设置 pieChart 图表基本属性
        binding.pie.setUsePercentValues(false);            //使用百分比显示
        binding.pie.getDescription().setEnabled(false);    //设置pieChart图表的描述
        binding.pie.setBackgroundColor(Color.WHITE);      //设置pieChart图表背景色
        binding.pie.setRotationAngle(0);                   //设置pieChart图表起始角度
        binding.pie.setRotationEnabled(false);              //设置pieChart图表是否可以手动旋转
        binding.pie.setHighlightPerTapEnabled(false);       //设置piecahrt图表点击Item高亮是否可用
        binding.pie.animateY(1000, Easing.EaseInOutQuad);// 设置pieChart图表展示动画效果
        // 设置 pieChart 图表Item文本属性
        binding.pie.setDrawEntryLabels(false);              //设置pieChart是否只显示饼图上百分比不显示文字（true：下面属性才有效果）
        // 设置 pieChart 内部圆环属性
        binding.pie.setDrawHoleEnabled(false);              //是否显示PieChart内部圆环(true:下面属性才有意义)

        // 获取pieCahrt图列
        Legend l = binding.pie.getLegend();
        l.setEnabled(false);                    //是否启用图列（true：下面属性才有意义）
        // pieChart添加数据
        List<Fragment> mFragments = new ArrayList<>();
        fragment1 = new LegendContentFragment();
        fragment2 = new LegendContentFragment();
        mFragments.add(0, fragment1);
        mFragments.add(1, fragment2);

        // 初始化ViewPager的适配器，并设置给它
        mViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
        binding.viewpager.setAdapter(mViewPagerAdapter);
        binding.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    setData(list1);
                } else {
                    setData(list2);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
        binding.tablayout.setTabsFromPagerAdapter(mViewPagerAdapter);
        binding.tablayout.post(new Runnable() {
            @Override
            public void run() {
                // 将TabLayout和ViewPager进行关联，让两者联动起来
                binding.tablayout.setupWithViewPager(binding.viewpager);
            }
        });


    }

    /**
     * 设置饼图的数据
     */
    private void setData(ArrayList<LegendBean> dataList) {
        ArrayList<PieEntry> pieEntryList = new ArrayList<PieEntry>();
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(Color.parseColor("#D9564C"));
        colors.add(Color.parseColor("#FDB52C"));
        colors.add(Color.parseColor("#2E9C7F"));
        colors.add(Color.parseColor("#3069A4"));
        //饼图实体 PieEntry
        for (LegendBean lb : dataList) {
            PieEntry CashBalance = new PieEntry(lb.getTypeScale().floatValue());
            pieEntryList.add(CashBalance);
        }

        //饼状图数据集 PieDataSet
        PieDataSet pieDataSet = new PieDataSet(pieEntryList, "");
        pieDataSet.setSliceSpace(5f);           //设置饼状Item之间的间隙
        pieDataSet.setSelectionShift(10f);      //设置饼状Item被选中时变化的距离
        pieDataSet.setColors(colors);           //为DataSet中的数据匹配上颜色集(饼图Item颜色)
        //最终数据 PieData
        PieData pieData = new PieData(pieDataSet);
        pieData.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
        pieData.setValueTextColor(Color.TRANSPARENT);  //设置所有DataSet内数据实体（百分比）的文本颜色
        pieData.setValueTextSize(0f);          //设置所有DataSet内数据实体（百分比）的文本字体大小
        pieData.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体（百分比）的文本字体格式
        binding.pie.setData(pieData);
        binding.pie.highlightValues(null);
        binding.pie.invalidate();                    //将图表重绘以显示设置的属性和数据
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.calendar:

                TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH)
                        .setTitleStringId("")
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.yellow))
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                        .setCallBack(this)
                        .build();
                visitFloorPicker.show(getSupportFragmentManager(), "year_month");

                break;
            case R.id.detail:
                Intent intent = new Intent(this, ListPushMoneyActivity.class);
                intent.putExtra("month", binding.calendar.getText().toString());
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        binding.calendar.setText(DateUtil.getTime(millseconds, "yyyy-MM"));
        getData();
    }

    private void getData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("creatTime", binding.calendar.getText().toString().concat("-01"));
        OkHttpUtils
                .postString()
                .url(ApiConfig.MY_COMMISSION)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(PushMoneyActivity.this, response)) {
                            ArrayList<LegendBean> dataList = JSON.parseObject(response.get("data").toString(), new TypeReference<ArrayList<LegendBean>>() {
                            });
                            binding.commissionAmount.setText("￥" + dataList.get(0).getSumAmount());
                            list1.clear();
                            list2.clear();
                            for (LegendBean lb : dataList) {
                                if (lb.getType().equals("person") || lb.getType().equals("train") || lb.getType().equals("develop")) {
                                    list2.add(lb);
                                } else {
                                    list1.add(lb);
                                }
                            }
                            setData(list1);
                            fragment1.setData(list1);
                            fragment2.setData(list2);

                        }
                    }
                });
    }
}

